package com.example.myapplication;

import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.util.HashMap;
import java.util.Set;

public class MainActivity extends AppCompatActivity {

    private WebView my_webview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        my_webview = findViewById(R.id.my_webview);
        my_webview.getSettings().setJavaScriptEnabled(true);
        my_webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true );
        my_webview.loadUrl("file:///android_asset/test.html");

        my_webview.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("MainActivity","url="+url);
                Uri uri = Uri.parse(url);
                if (uri.getScheme().equals("js")){
                    if (uri.getAuthority().equals("webview")){
                        Log.e("MainActivity","通过协议调用到了按照代码");
                        HashMap<String,String> params = new HashMap<>();
                        Set<String> collection = uri.getQueryParameterNames();
                        Log.e("MainActivity","collection="+collection.toString());
                        return true;
                    }
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        my_webview.addJavascriptInterface(new AndroidtoJS(MainActivity.this),"test");

        my_webview.setWebChromeClient(new WebChromeClient(){
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
                        .setTitle("JS Alert")
                        .setMessage(message)
                        .create();
                alertDialog.show();
                return true;
//                return super.onJsAlert(view, url, message, result);
            }
        });

        findViewById(R.id.btn_callwebjs).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                my_webview.loadUrl("javascript:callJS()");

                my_webview.evaluateJavascript("javascript:callJS()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String value) {

                    }
                });
            }
        });
    }
}
